package com.ly.heart.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.ly.common.PageParam;
import com.ly.common.core.domain.AjaxResult;
import com.ly.common.exception.CustomException;
import com.ly.common.utils.DateUtils;
import com.ly.common.utils.SecurityUtils;
import com.ly.common.utils.StringUtils;
import com.ly.common.utils.erp.ConstUtil;
import com.ly.common.utils.erp.SnowflakeIdWorker;
import com.ly.heart.domain.ActTaskCommentEntity;
import com.ly.heart.domain.ContractAdminEntity;
import com.ly.heart.domain.dto.StartProcessDto;
import com.ly.common.core.domain.ActCurrentTaskVo;
import com.ly.heart.mapper.ContractAdminMapper;
import com.ly.heart.service.IActModelService;
import com.ly.heart.service.IActTaskCommentService;
import com.ly.heart.service.IContractAdminService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Optional;

/**
 * <p>
 * 行政合同 服务实现类
 * </p>
 * @author WuZH
 * @since 2024-08-25
 */
@Service
public class ContractAdminServiceImpl extends ServiceImpl<ContractAdminMapper, ContractAdminEntity> implements IContractAdminService {

    @Resource
    private IActModelService iActModelService;
    @Resource
    private ContractAdminMapper contractAdminMapper;
    @Resource
    private IActTaskCommentService iActTaskCommentService;

    @Override
    public AjaxResult queryList (ContractAdminEntity contractAdminEntity) {
        contractAdminEntity.setPage ( ( contractAdminEntity.getPage () - 1 ) * contractAdminEntity.getLimit () );
        contractAdminEntity.setIsUsed ( ConstUtil.IS_USED_YES );
        List<ContractAdminEntity> contractAdminEntities = contractAdminMapper.queryList ( contractAdminEntity );
        contractAdminEntities.forEach ( contract -> {
            //处理最后一个审批人
            ActTaskCommentEntity actTaskCommentEntity = iActTaskCommentService.queryLastComment ( contract.getInstanceId () );
            if ( actTaskCommentEntity != null ) {
                contract.setApprovedUser ( actTaskCommentEntity.getApprovedUser () );
                contract.setApprovedRemark ( actTaskCommentEntity.getRemark () );
            }
            //任务信息
            ActCurrentTaskVo currentTaskVo = iActModelService.getCurrentTaskByInstanceId( contract.getInstanceId());
            Optional.ofNullable( currentTaskVo).ifPresent( currentTask -> {
                contract.setCurrentTask(currentTask);
            });
        } );
        Integer count = contractAdminMapper.queryCount ( contractAdminEntity );
        PageParam p = new PageParam ();
        p.setRecords ( contractAdminEntities ).setTotal ( count );
        return AjaxResult.success ( p );
    }

    @Override
    public ContractAdminEntity querySingle (String id) {
        ContractAdminEntity contract = contractAdminMapper.querySingle ( id );
        return contract;
    }

    @Override
    public AjaxResult draft (ContractAdminEntity contractAdminEntity) {
        contractAdminEntity.setId ( SnowflakeIdWorker.getInstance ().nextStringId () );
        int count = this.count ();
        contractAdminEntity.setContractNumber ( "XZHT".concat ( String.format ( "%08d", count ) ) );
        contractAdminEntity.setCreateBy ( SecurityUtils.getLoginUser ().getUser ().getUserId () );
        contractAdminEntity.setCreateTime ( DateUtils.getNowDate () );
        contractAdminEntity.setState ( ConstUtil.STATE_IN_DRAFT );
        boolean save = this.save ( contractAdminEntity );
        if ( ! save ) {
            throw new CustomException ( "暂存行政合同失败！" );
        }
        return AjaxResult.success ( "暂存行政合同成功", contractAdminEntity.getId () );
    }

    @Override
    public AjaxResult submit (ContractAdminEntity contractAdminEntity) {
        if ( StringUtils.isBlank ( contractAdminEntity.getId () ) ) {
            return AjaxResult.error ( "请先暂存该单据！" );
        }
        //创建审批流
        StartProcessDto startDto = new StartProcessDto ().
                setBusinessId ( contractAdminEntity.getId () ).
                setBusinessType ( contractAdminEntity.getBusinessType () ).setModelId ( contractAdminEntity.getModelId () ).
                setBusinessName ( "采购合同_".concat ( contractAdminEntity.getId () ) );
        String instanceId = iActModelService.startProcess ( startDto );
        contractAdminEntity.setInstanceId ( instanceId );
        boolean update = this.update ( new LambdaUpdateWrapper<ContractAdminEntity> ().
                set ( ContractAdminEntity :: getInstanceId, instanceId ).
                set ( ContractAdminEntity :: getState, ConstUtil.STATE_IN_PROCESS ).
                eq ( ContractAdminEntity :: getId, contractAdminEntity.getId () ) );
        if ( ! update ) {
            throw new CustomException ( "提交行政合同失败！" );
        }
        return AjaxResult.success ();
    }

    @Override
    public AjaxResult updateSingle (ContractAdminEntity contractAdminEntity) {
        contractAdminEntity.setUpdateBy ( SecurityUtils.getLoginUser ().getUser ().getUserId () );
        contractAdminEntity.setUpdateTime ( DateUtils.getNowDate () );
        boolean b = this.updateById ( contractAdminEntity );
        if ( ! b ) {
            throw new CustomException ( "修改行政合同失败！" );
        }
        return AjaxResult.success ();
    }

    @Override
    public AjaxResult deleteByIds (String[] ids) {
        boolean update = this.update ( new LambdaUpdateWrapper<ContractAdminEntity> ().
                set ( ContractAdminEntity :: getIsUsed, ConstUtil.IS_USED_NO ).
                in ( ContractAdminEntity :: getId, ids ) );
        if ( ! update ) {
            throw new CustomException ( "删除行政合同失败！" );
        }
        return AjaxResult.success ();
    }
}
